package com.zzt.questionbankquestion.bean.dto.query;

import com.zzt.questionbankquestion.bean.QuestionType;
import lombok.Data;
import org.springframework.data.jpa.domain.Specification;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Data
public class QuestionTypeQueryDTO  {
    private String questionTypeName;
    private Integer page;
    private Integer size;

    public Specification< QuestionType > getWhereClause(){
        String questionTypeName=this.questionTypeName;
        return new Specification< QuestionType >() {
            private static final long serialVersionUID = 1L;
            @Override
            public Predicate toPredicate(Root< QuestionType > root, CriteriaQuery< ? > criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(questionTypeName)){
                    predicates.add(criteriaBuilder.like(root.get("questionTypeName").as(String.class), "%"+questionTypeName+"%"));
                }
                Predicate[] pre = new Predicate[predicates.size()];
                return criteriaQuery.where(predicates.toArray(pre)).getRestriction();
            }
        };
    }
}
